<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Kra8\Snowflake\HasSnowflakePrimary;

class Device extends Model
{
    use SoftDeletes;
    use HasSnowflakePrimary;

    protected $fillable = [
        'user_id',
        'cover',
        'name',
        'device_group_id',
        'device_order_id',
        'status',
        'style',
        'mac_address',
        'unique_id',
        'connection_password',
        'province',
        'city',
        'area',
        'recent_usage_time',
        'recent_repair_time'
    ];

    public function author()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

    public function device_order()
    {
        return $this->belongsTo('App\Models\DeviceOrder', 'device_order_id');
    }

    public function device_group()
    {
        return $this->belongsTo('App\Models\Group', 'device_group_id');
    }

    public function logs()
    {
        return $this->hasMany('App\Models\DeviceLog', 'device_id');
    }

    public function repair_logs()
    {
        return $this->hasMany('App\Models\DeviceRepairLog', 'device_id');
    }

    public function covers()
    {
        return $this->hasMany('App\Models\DeviceCoverLog', 'device_id');
    }

    public function getPriceSpecificationsAttribute()
    {
        $items = PriceSpecification::where('style', $this->style)->where(function ($query) {
            $query->where('province', $this->province)
                ->where('city', $this->city)
                ->where('area', $this->area)
                ->orWhere('cate', 'NORMAL');
        })
            ->get();
        return $items;
    }

    public function getMarketingPoliciesAttribute()
    {
        if (in_array(request()->header('mode'), ['wechats'])) {
            $authUser = auth()->user();
            if ($authUser->role === 'PARTNER') {
                $policy = MarketingPolicy::where('target', 'PARTNER')->latest('updated_at')->first();
                if ($policy) {
                    return $policy;
                }
            }
            $policy = MarketingPolicy::where('target', 'MEMBER')->latest('updated_at')->first();
            return $policy;
        }
        return null;
    }
}
